<template>
  <HDialog v-model="visible" :loading="loading" title="预约时间" @close="onCancel">
    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      @validate="handleFormValidate"
      class="modal_form_content"
      inline-message
      label-position="top"
    >
      <el-form-item label="预约上门日期" prop="date">
        <el-date-picker
          v-model="ruleForm.date"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="预约上门日期"
          size="small"
        />
      </el-form-item>
      <el-form-item label="预约上门时间" prop="reservationStartTime">
        <div class="time_container">
          <el-time-select
            v-model="ruleForm.reservationStartTime"
            :max-time="ruleForm.reservationEndTime"
            :placeholder="getReservationRangeLoading ? '获取时间范围中' : '开始时间'"
            :start="timeSelectRangeStart"
            step="02:00"
            :end="timeSelectRangeEnd"
            class="time_picker"
            :disabled="getReservationRangeLoading"
          />
          <div class="separator"> ~ </div>
          <el-time-select
            v-model="ruleForm.reservationEndTime"
            :min-time="ruleForm.reservationStartTime"
            :placeholder="getReservationRangeLoading ? '获取时间范围中' : '结束时间'"
            :start="timeSelectRangeStart"
            step="02:00"
            :end="timeSelectRangeEnd"
            class="time_picker"
            :disabled="getReservationRangeLoading"
          />
        </div>
      </el-form-item>
      <el-form-item label="预约留言">
        <el-input
          v-model.trim="ruleForm.remark"
          maxlength="100"
          placeholder="请输入预约留言"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <HButton is-modal type="primary" @click="onSave">保存</HButton>
      <HButton is-modal @click="onCancel"> 取消 </HButton>
    </template>
  </HDialog>
</template>

<script setup lang="ts">
  import { ref, toRefs, reactive, watch, computed } from 'vue'
  import { ElMessage, FormItemProp } from 'element-plus'
  import { reservationTime, getReservationRange } from '@/api/order'

  const props = defineProps({
    modelValue: Boolean,
    workId: String || Object,
  })
  const { workId } = toRefs(props)
  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'update:modelValue', value: boolean): void
  }>()
  const loading = ref(false)
  const visible = ref(false)

  const formRef = ref()
  const ruleForm = reactive({
    date: '',
    remark: '',
    reservationStartTime: '',
    reservationEndTime: '',
    workId: workId.value,
  })
  const rules = reactive({
    date: [{ required: true, message: '请选择预约上门日期！', trigger: ['blur', 'change'] }],
    reservationStartTime: [
      { required: true, message: '请选择预约上门时间！', trigger: ['blur', 'change'] },
    ],
    reservationEndTime: [
      { required: true, message: '请选择预约上门时间！', trigger: ['blur', 'change'] },
    ],
  })

  // 保存
  const onSave = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        let data: any = ruleForm
        await reservationTime(data).then((res) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (res.data.success) {
            emits('update')
            onCancel()
          }
        })
        loading.value = false
      } else {
        return false
      }
    })
  }
  const onCancel = () => {
    formRef.value.resetFields()
    formValidateResult.value = {
      date: true,
      reservationStartTime: true,
    }
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  const reservationRange = ref<{
    reservationEndTime: string
    reservationStartTime: string
    reservationTimeType: number
  } | null>(null)

  // 获取预约时间范围加载
  const getReservationRangeLoading = ref(false)

  /**
   * 获取预约时间范围方法
   * @param {string} workId - 工单id
   */
  const getReservationRangeFn = async (workId: string) => {
    getReservationRangeLoading.value = true
    const res = await getReservationRange(workId)
    reservationRange.value = res.data.data
    getReservationRangeLoading.value = false
  }

  // 时间选择器开始时间
  const timeSelectRangeStart = computed(() => {
    if (!reservationRange.value) return '06:00'
    if (reservationRange.value.reservationTimeType === 3) {
      return reservationRange.value.reservationStartTime
    }
    return '06:00'
  })

  // 时间选择器结束时间
  const timeSelectRangeEnd = computed(() => {
    if (!reservationRange.value) return '22:00'
    if (reservationRange.value.reservationTimeType === 3) {
      return reservationRange.value.reservationEndTime
    }
    return '22:00'
  })

  const formValidateResult = ref({
    date: true,
    reservationStartTime: true,
  })
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    formValidateResult.value[prop as string] = isValid
  }

  watch(
    props,
    (value) => {
      visible.value = value.modelValue
      if (value.modelValue) {
        getReservationRangeFn(props.workId)
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  :deep(.el-textarea) {
    .el-textarea__inner {
      width: 100% !important;
      height: 85px !important;
    }
  }

  .time_container {
    display: flex;
    width: 100%;
    justify-content: space-between;
    gap: 5px;
    height: 28px;
  }

  :deep(.el-input) {
    height: 28px;
    width: 100%;

    .el-input__wrapper {
      height: 26px;
    }
  }
</style>
